#include "textfieldwin.h"
#include "ui_textfieldwin.h"
#include "gs/globalshortcutmanager.h"
#include "mainobject.h"

TextFieldWin::TextFieldWin(QWidget *parent)
    : QDialog(parent, Qt::Widget
              ), ui(new Ui::TextFieldWin)
{
    applyWindowFlags();
    ui->setupUi(this);
    mover = new WindowMover(this, EN_TEXT_POS);
    installEventFilter(this);
    installEventFilter(ui->lineEdit);
}

void TextFieldWin::applyWindowFlags(){
    QSettings settings;
    Qt::WindowFlags flags = Qt::Widget | Qt::FramelessWindowHint;
#ifdef Q_OS_WIN32
    flags |= Qt::Tool;
#endif
    if(settings.value(EN_ONTOP, EN_ONTOP_DEF).toBool())
        flags |= Qt::WindowStaysOnTopHint;
    setWindowFlags(flags);
}

bool TextFieldWin::eventFilter(QObject *object, QEvent *event){
    QSettings settings;
    if(event->type()==QEvent::DragEnter){
        QDropEvent *dndEvent = dynamic_cast<QDropEvent*>(event);
        object->dumpObjectInfo();
        qDebug() << "Drag enter" << object->staticMetaObject.className() << dndEvent->mimeData()->formats();
        if(dndEvent->mimeData()->hasHtml() ||
           dndEvent->mimeData()->hasText() ||
           dndEvent->mimeData()->hasUrls())
            dndEvent->accept();
    }
    if(event->type()==QEvent::Drop){
        qDebug() << "Drop!";
        QDropEvent *dndEvent = dynamic_cast<QDropEvent*>(event);
        QSettings settings;
        QStringList tags;
        QStringList optTags = settings.value(EN_FILE_TAGS).toString().split(" ", QString::SkipEmptyParts);
        tags.append(optTags);
#ifdef Q_OS_MAC
//        if(dndEvent->mimeData()->hasHtml()){
//            qDebug() << "Saving html";
//            MainObject::instance()->createTextNote(dndEvent->mimeData()->html(),
//                                                   settings.value(EN_FILE_NB).toString(),
//                                                   "Drop at "+QDateTime::currentDateTime().toString("dd.MM.yy hh:mm:ss"),
//                                                   "html", tags);
//            return true;
//        }
#endif
        if(dndEvent->mimeData()->hasText()){
            QDateTime dateTime;
//            qDebug() << "Saving plain text" << QDateTime::currentDateTime().toString("dd.MM.yy hh:mm:ss");

            if(MainObject::instance()->createTextNote(dndEvent->mimeData()->text(),
                                                   settings.value(EN_FILE_NB).toString(),
                                                   "Drop at "+QDateTime::currentDateTime().toString("dd.MM.yy hh:mm:ss"),
                                                   "txt", tags)){
//                    MainObject::instance()->trayIcon->showMessage("Evernote trap",
//                                                                  "Drop added to Evernote",
//                                                                  QSystemTrayIcon::Information, 1000);
            }
            return true;
        }
        if(dndEvent->mimeData()->hasUrls()){
            QList<QUrl> urls = dndEvent->mimeData()->urls();
//            qDebug() << "Saving URIs" << urls.size();
            for(int i = 0; i<urls.size(); i++){
                qDebug() << urls[i].scheme() << urls[i].toLocalFile();
                if(MainObject::instance()->createFileNote(urls[i].toLocalFile(),
                                                       settings.value(EN_FILE_NB).toString(), "", tags)){
//                    MainObject::instance()->trayIcon->showMessage("Evernote trap",
//                                                                  "File "+urls[i].toLocalFile()+" added to Evernote",
//                                                                  QSystemTrayIcon::Information, 1000);
                }
            }
        }
    }
    if(event->type()==QEvent::WindowActivate){
        setWindowOpacity(settings.value(EN_ACTIVE_OPACITY, EN_ACTIVE_OPACITY_DEF).toInt()/(double)100);
//        qDebug() << "Window activated" << windowOpacity();
    }
    if(event->type()==QEvent::WindowDeactivate){
        setWindowOpacity(settings.value(EN_INACTIVE_OPACITY, EN_INACTIVE_OPACITY_DEF).toInt()/(double)100);
//        qDebug() << "Window deactivated" << windowOpacity();
    }
    return mover->eventFilter(object, event);
}

TextFieldWin::~TextFieldWin()
{
    delete mover;
    delete ui;
}

void TextFieldWin::keyPressEvent(QKeyEvent *event){
    switch(event->key()){
        case Qt::Key_Return:
            if(ui->lineEdit->text().trimmed()!=""){
                qDebug() << "Ready to add note";
                QSettings settings;
                QStringList tags;
                QStringList optTags = settings.value(EN_TEXT_TAGS).toString().split(" ", QString::SkipEmptyParts);
                tags.append(optTags);
                QString note = ui->lineEdit->text().trimmed();
                QStringList words = note.split(" ", QString::SkipEmptyParts);
                QString nb = settings.value(EN_TEXT_NB).toString();
                for(int i = words.size()-1; i>=0; i--){
                    QString word = words[i];
                    if(word.startsWith('@')){
                        word.remove(0, 1);
                        note.resize(note.lastIndexOf(word)-1);
                        if(!tags.contains(word))
                            tags.append(word);
                    }else{
                        if(word.startsWith('>')){
                            word.remove(0, 1);
                            note.resize(note.lastIndexOf(word)-1);
                            QStringList notebooks = MainObject::instance()->getNotebooks();
                            for(int j = 0; j < notebooks.size(); j++) {
                                if(notebooks[j].toLower().startsWith(word.toLower())){
                                    nb = notebooks[j];
                                    break;
                                }
                            }
                        } else {
                            break;
                        }
                    }
                }
                MainObject::instance()->createTextNote(note, nb,
                                                       note, "txt", tags);
                ui->lineEdit->setText("");
            }
        break;
        case Qt::Key_Escape:
            if(ui->lineEdit->text().trimmed()!=""){
                ui->lineEdit->setText("");
            }else{
                hide();
            }
        break;
        default:
            QDialog::keyPressEvent(event);
    }
}

void TextFieldWin::show(){
    ui->lineEdit->setText("");

    QSettings settings;
    int x = settings.value(QString(EN_TEXT_POS)+QString("_X"), 0).toInt();
    int y = settings.value(QString(EN_TEXT_POS)+QString("_Y"), 0).toInt();
    move(x, y);
    resize(settings.value(EN_POS_WIDTH, EN_POS_WIDTH_DEF).toInt(),
           settings.value(EN_POS_HEIGHT, EN_POS_HEIGHT_DEF).toInt());
    QDialog::show();
    QRect screen = QApplication::desktop()->screenGeometry(this);
    if(screen.x()>=x || screen.y()>=y
       || screen.x()+screen.width()<=x+width()
       || screen.y()+screen.height()<=y+height()){
        x = (screen.width()-width())/2+screen.x();
        y = (screen.height()-height())/2+screen.y();
    }
    move(x, y);
    settings.setValue(EN_TEXT_VISIBLE, true);
    activate();
}

void TextFieldWin::activate(){
    raise();
    activateWindow();
    ui->lineEdit->setFocus(Qt::OtherFocusReason);
}

void TextFieldWin::hide(){
    QDialog::hide();
    QSettings settings;
    settings.setValue(EN_TEXT_VISIBLE, false);
}

void TextFieldWin::resizeEvent(QResizeEvent *event){
    QSettings settings;
    qDebug() << event->size();
    settings.setValue(EN_POS_WIDTH, event->size().width());
    settings.setValue(EN_POS_HEIGHT, event->size().height());
    QDialog::resizeEvent(event);
}
